<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'partner' => '2088621781822784',//用不着
        'seller_id' => 'admin@bagepanzi.com',//用不着
        'sign_type' => 'RSA2',// 直接写死了
        'it_b_pay' => '10m',//用不着
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqP3RSHJuQcjitVbRqOu7OI5rl7+bqTDbpWgWECwjLpDHvG2YhVuwOpRWZ+Ix4EH5WKIdQv1zGOZstWHkIQD4JyBIASj9vp3R3noSUkab31/Yp4fjJOzdgIO7Ldh4mwGhxW4oXLRg3GajR0FlFfvBMglkozcbe2MRxA6KAWauouTjJPTME4429oCLNMJlckMwxA2DFzbH6pBge/+sLpocJbGDEKngid04gidKs5tJ+Oif2JRTJcHe+qsMQQOLRiWE/YIVHE8QggPljBoVjY/c7ezBBe1ERfiX9rUImFx7mYnAePt/45fuhpdatRS74TdkvicaJ0YCVGxHCc+Ez3zNMQIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwZp4bJH3Jovh59yodKEm+QRmuA+CLOTlEU/XmtVhDN0/U4AZBl54I+9zZifVmKHfnUBjdE7MbMLPGwRiklPM2ByPS/0Nnz3YZoSz0dpZg46IXCqAIThs9WI+OB/tVeZAFThRbHb2c7yEgK8fOwmX1iAwHo2yNQcT/Z+9OPH2wp6zQ5bAAcIMBK7Ewm5ZM+sddeHDiYVulX5MwEUqDk+jkK0L2COhpEh2peb97sOa4lAI0r1egwELRspMNZfqZorQPelL0IjRmOPRh1AhbCtw8lV/NvY1smGmuxiRR1LlAr3kiO4DBgbb6D+zM2JNSChawO7X0Avxm8u5f+aVOrCUpQIDAQAB",
        'private_key' => 'MIIEpAIBAAKCAQEAwZp4bJH3Jovh59yod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eKfQsG6r2XbXNRokBVKyQ5kupCwNx0dB2WvvwgaeNudcY6rdKsfCCqNtj1rau6BNuSdUC9bKT64LamOI0mOwSMmULk/zokH6WbRk5w9ZtdkDdhMtxZmrakw5CmykCgYEAyQ7FMr+aGjY19U0zG5f9LZmys/Iv+iVKzXoCA6IqmerOvCx8LMcodpUWi5n1SOtefr+bZtZbDURkgZ8e0HKSGeg6XfqQR+fVpbCEtPbUgtqjy8oMlTtUn4UOR7WD05fu/1UfaIFA3JeQ5Uk0ZevffTqKblp0fHUE8tkoYJA8z8ECgYAtLZSkSDepPhwqcENISknkUm8QOS0PwssRqt7GNO/TUaw3UR0M1cnAne4VyyIyi3VLu7YpXn5/zWNNI8ISYQUUHBE4mymfWL7qLPAmVhYL1cqko29n38cm3SgJp1G2On/dfxiTQVi1XdcfnCq8Z8JC7KOr4WGDbrCVhGZnfWErZg=='
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//喵额
    public $out_trade_no;//订单号
    
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);

        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = "2019080566158002";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://mass.xuanwumobile.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msgsss'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msgsss'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    /**
     * 生成订单
     * @return
     * user_id：用户ID,
     * type：1 课程购买  2 捐赠  3 打赏
     * price：打赏或捐赠的价格，当type为2或者3时传
     * activity_id：捐赠的活动ID，当type为2时，传此值
     */
    public function alipay()
    {
        extract(input());
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == 112) {
            return json(['status' => 301, 'msg' => $this->otherLogin]);
        }elseif($res == 110){
            return json(['status' => 302, 'msg' => $this->frost]);
        }elseif($res == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
            $order_number = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);//订单编号
            $data['order_cate'] =1;
            $data['order_type'] =1;
            $data['order_num'] =$order_number;
            $data['order_money'] =$params['answer_money'];
            $data['order_time'] =date('Y-m-d H:i:s',time());
            $data['order_user_id'] =$params['user_id'];
            Db::table('up_order')->insertGetId($data);
            $this->body = '响哨悬赏问答';
            $this->subject = '响哨悬赏问答';
//            $this->total_amount =$params['answer_money'];
            $this->total_amount =0.1;
            $this->out_trade_no = $order_number;
            $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
            return json_encode($respont);
    }
    
    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                Db::startTrans();
                try{
                    $num = $getInfo['out_trade_no'];//订单号
                    $dataAll = Db::table('up_order')->where('order_num',$num)->find();
                    if($dataAll['order_id']!=''){
                        $data['order_pay_time'] = date('Y-m-d H:i:s',time());
                        $data['order_status'] = 2;
                        Db::table('up_order')->where('order_id',$dataAll['order_id'])->update($data);
                        Db::commit();
                        die('success');
                    }
                }catch(\Exception $e){
                    Db::rollback();//回滚
                    return 'error';
                }
            }
        }
    }


    /**
     *支付宝的原路退款接口(商户处理用户的订单)
     */
    public function refund(){
        $payInfo = array();
        $payInfo['number'] = '201905311701374074';
        $payInfo['money'] = 12;
        //仨参数：money,number
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2019080566158002';
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['public_key']; //不应该用这个，用ali_public
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest;
        $refundAmount = $payInfo['money'];
        $request->setBizContent("{" .
            "\"out_trade_no\":\"".$payInfo['number']."\"," .
            "\"trade_no\":\"\"," .
            "\"refund_amount\":".$refundAmount."," .
            "\"refund_reason\":\"退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && $resultCode == 10000){
            return array('status'=>200,'msg'=>'操作成功');
        }else{
            return array('status'=>0,'msg'=>'调用接口失败');
        }
    }
}